#include "AuClient.h"
#include "Message.h"
#include <string.h>
#include <iostream>
#include "JsonUtil.h"
using namespace std;
AuClient::AuClient(/* args */)
{
    this->socket=new TcpSocket;
}

Response *AuClient::execute(Request &request)
{
    //客户端与服务端链接
    this->socket->connectServe(request.getIp(),request.getPort(),3000);
    //封装Message
    map<string,string> paramMap=request.getData();
    string content=JsonUtil::mapParseStr(paramMap);
    Message message;
    message.content=(char*)content.c_str();
    message.type=request.getContentType();
    message.length=strlen(message.content);

    //通过TcpSocket向服务端发起请求
    int len=this->socket->sendMag(&message,3000);
    Message *msg=this->socket->receiveMag(3000);
    Response *response=nullptr;
    if (msg->type==0)
    {
        char *data=msg->content;
        map<string,string> resMap=JsonUtil::strjsonParseMap(data);
        int code=atoi(resMap["code"].c_str());
        bool success=atoi(resMap["success"].c_str());
        string message=resMap["message"];
        string filedata=resMap["data"];
        response =new Response(code,success,message,filedata);
    }else
    {
        if (msg->length==-1)
        {
            cout<<"下载失败"<<endl;
            response=new Response(728,false,"下载失败",NULL);
        }else
        {
            FileContent *fileContent=new FileContent;
            fileContent->content=msg->content;
            fileContent->length=msg->length;
            response=new Response(728,true,"下载成功",fileContent);
        }
        
    }
    
    return response;
}

AuClient::~AuClient()
{
    if (this->socket!=nullptr)
    {
        delete this->socket;
    }
}
